<?php

namespace Icsoc\DataBundle\Model;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * Class EvaluatemModel
 * @package Icsoc\DataBundle\Model
 */
class EvaluatemModel extends BaseModel
{
    /** @var ContainerInterface */
    public $container;

    /** @var \Doctrine\DBAL\Connection  */
    private $dbal;

    /** @var \Symfony\Bridge\Monolog\Logger  */
    private $logger;

    /**
     * 录音呼叫类型
     * @var array
     */
    private $RCALLTYPE = array(
        '1' => '呼出',
        '2' => '呼入',
    );

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->dbal = $container->get('doctrine.dbal.default_connection');
        $this->logger = $container->get('logger');
    }

    /**
     * @param array $param
     * @return array|string
     */
    public function evaluateList(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $param['info'];

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message'=>'info格式非json');
            }
        }

        $where = '';

        if (isset($addInfo['filter'])) {
            if (isset($addInfo['filter']['keyword']) && !empty($addInfo['filter']['keyword'])) {
                $where.=" AND name LIKE '%".$addInfo['filter']['keyword']."%' ";
            }
        }

        $count = $this->dbal->fetchColumn(
            'SELECT count(*) FROM cc_evaluates WHERE vcc_id = :vid '.$where,
            array('vid'=>$vid)
        );

        $sounds = $this->container->get('icsoc_data.model.sound')->getSoundsArray($vid);
        $soundsArr = array();
        foreach ($sounds as $sound) {
            $soundsArr[$sound['id']] = $sound['name'];
        }

        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'cc_evaluates', $addInfo);

        $result = $this->dbal->fetchAll(
            'SELECT id,name,sound_id,play_order,retry_times,valid_keys FROM cc_evaluates WHERE vcc_id = :vcc_id '.$where.'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vcc_id' => $vid)
        );

        $list = array();
        foreach ($result as $k => $v) {
            $list[$k] = $v;
            $list[$k]['sound_id'] = isset($soundsArr[$v['sound_id']]) ? $soundsArr[$v['sound_id']] : '';
        }

        return array('code'=>200, 'message'=>'ok', 'total'=>$count, 'data'=>$list, 'totalPage'=>$page['totalPage']);
    }

    /**
     * @param array $param
     * @return array
     */
    public function add(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $name = empty($param['name']) ? 0 : trim($param['name']);
        $soundId = empty($param['sound']) ? 0 : trim($param['sound']);
        $playOrder = empty($param['play_order']) ? 0 : trim($param['play_order']);
        $retryTimes = empty($param['retry_times']) ? 0 : trim($param['retry_times']);
        $validKeys = empty($param['valid_keys']) ? '' : trim($param['valid_keys']);

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($name)) {
            return array('code'=>402, 'message'=>'满意度名称为空');
        }

        if (empty($soundId)) {
            return array('code'=>404, 'message'=>'语音文件为空');
        }

        $this->dbal->beginTransaction();

        try {
            $data['vcc_id'] = $vid;
            $data['name'] = $name;
            $data['sound_id'] = $soundId;
            $data['play_order'] = $playOrder;
            $data['retry_times'] = $retryTimes;
            $data['valid_keys'] = $validKeys;
            $this->dbal->insert('cc_evaluates', $data);
            $id = $this->dbal->lastInsertId();
            $this->dbal->commit();

            $logStr = array('id'=>$id);
            foreach ($data as $key => $v) {
                if ($key != 'vcc_id') {
                    $logStr[] = $key.'=>'.$v;
                }
            }

            $content = $this->container->get('translator')->trans(
                "Add Evaluates Setting %evaluate_info%",
                array('%evaluate_info%'=>implode(',', $logStr))
            );

            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_ADD, $content);

            return array('code'=>200, 'message'=>'ok');

        } catch (\Exception $e) {
            $this->dbal->rollBack();
            $this->logger->error($e->getMessage());

            return array('code'=>404, 'message'=>'数据保存失败');
        }
    }

    /**
     * @param array $param
     * @return array
     */
    public function update(array $param = array())
    {
        $vccCode = $param['vccCode'];
        $evaluateConfig = $param['evaluateConfig'];

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($evaluateConfig)) {
            return array('code'=>402, 'message'=>'满意度配置为空');
        }


        $evaluateConfigs = json_decode($evaluateConfig, true);
        if (json_last_error()) {
            return array('code' => 403, 'message'=>'满意度配置格式非json');
        }

        $res = $evaluateConfigs;
        $arr = $this->getEvaluateId($vid);
        $id = $arr['id'];
        $action = $arr['action'];
        $index = 1;

        foreach ($evaluateConfigs as $evaluate => $evaluateConfig) {
            if (isset($evaluateConfig['evaluate_type'])) {
                if ($evaluateConfig['evaluate_type'] == 1) {
                    $res[$evaluate]['id'] = 'evaluate-'.$id.'-'.$index;
                    $res[$evaluate]['play_times'] = 3;
                    $res[$evaluate]['sound_id'] = 1;
                    $res[$evaluate]['sound_address'] = '/var/sounds/evaluate_default1.wav';

                    $res[$evaluate]['keys'][1]['id'] = 'evaluate-'.$id.'-'.$index.'-1';
                    $res[$evaluate]['keys'][1]['play_times'] = 3;
                    $res[$evaluate]['keys'][2]['id'] = 'evaluate-'.$id.'-'.$index.'-2';
                    $res[$evaluate]['keys'][2]['play_times'] = 3;
                } else if ($evaluateConfig['evaluate_type'] == 2) {
                    $res[$evaluate]['id'] = 'evaluate-' . $id . '-' . $index;
                    $res[$evaluate]['play_times'] = 3;
                    $res[$evaluate]['sound_id'] = 2;
                    $res[$evaluate]['sound_address'] = '/var/sounds/evaluate_default2.wav';

                    $res[$evaluate]['keys'][1]['id'] = 'evaluate-' . $id . '-' . $index . '-1';
                    $res[$evaluate]['keys'][1]['play_times'] = 3;
                    $res[$evaluate]['keys'][2]['id'] = 'evaluate-' . $id . '-' . $index . '-2';
                    $res[$evaluate]['keys'][2]['play_times'] = 3;
                    $res[$evaluate]['keys'][3]['id'] = 'evaluate-' . $id . '-' . $index . '-3';
                    $res[$evaluate]['keys'][3]['play_times'] = 3;
                } else if ($evaluateConfig['evaluate_type'] == 3) {
                    $res[$evaluate]['id'] = 'evaluate-' . $id . '-' . $index;
                    $res[$evaluate]['play_times'] = 3;
                    $res[$evaluate]['sound_id'] = 3;
                    $res[$evaluate]['sound_address'] = '/var/sounds/evaluate_default3.wav';

                    $res[$evaluate]['keys'][1]['id'] = 'evaluate-' . $id . '-' . $index . '-1';
                    $res[$evaluate]['keys'][1]['play_times'] = 3;
                    $res[$evaluate]['keys'][2]['id'] = 'evaluate-' . $id . '-' . $index . '-2';
                    $res[$evaluate]['keys'][2]['play_times'] = 3;
                    $res[$evaluate]['keys'][3]['id'] = 'evaluate-' . $id . '-' . $index . '-3';
                    $res[$evaluate]['keys'][3]['play_times'] = 3;
                    $res[$evaluate]['keys'][4]['id'] = 'evaluate-' . $id . '-' . $index . '-4';
                    $res[$evaluate]['keys'][4]['play_times'] = 3;
                    $res[$evaluate]['keys'][5]['id'] = 'evaluate-' . $id . '-' . $index . '-5';
                    $res[$evaluate]['keys'][5]['play_times'] = 3;
                }
            } else {
                //自定义满意度
                $res[$evaluate]['id'] = 'evaluate-'.$id.'-'.$index;
                $res[$evaluate]['play_times'] = 3;
                $res[$evaluate]['sound_address'] = $this->getSoundAddress($res[$evaluate]['sound_id']);
                foreach ($res[$evaluate]['keys'] as $otherId => $otherConfig) {
                    $res[$evaluate]['keys'][$otherId]['id'] = 'evaluate-'.$id.'-'.$index.'-'.$otherId;
                    $res[$evaluate]['keys'][$otherId]['play_times'] = 3;
                    if (!empty($otherConfig['child'])) {
                        $res[$evaluate]['keys'][$otherId]['child']['id'] = 'evaluate-'.$id.'-'.$index.'-'.$otherId;
                        $res[$evaluate]['keys'][$otherId]['child']['play_times'] = 3;
                        $res[$evaluate]['keys'][$otherId]['child']['sound_address'] = $this->getSoundAddress(
                            $res[$evaluate]['keys'][$otherId]['child']['sound_id']
                        );
                        foreach ($otherConfig['child']['keys'] as $childId => $childConfig) {
                            $res[$evaluate]['keys'][$otherId]['child']['keys'][$childId]['id'] = 'evaluate-'.$id.'-'.$index.'-'.$otherId.'-'.$childId;
                            $res[$evaluate]['keys'][$otherId]['child']['keys'][$childId]['play_times'] = 3;
                        }
                    }
                }
                $index++;
            }
        }
        $evaluateConfig = json_encode($res);

        $this->dbal->beginTransaction();
        try {
            $data['evaluate_config'] = $evaluateConfig;
            if ($action == 'update') {
                $this->dbal->update('cc_evaluates_config', $data, array('vcc_id' => $vid));
            } else {
                $data['vcc_id'] = $vid;
                $this->dbal->insert('cc_evaluates_config', $data);
            }

            $this->dbal->commit();
            $logStr = array('vcc_id'=> $vid);
            foreach ($data as $key => $v) {
                if ($key != 'vcc_id') {
                    $logStr[] = $key.'=>'.$v;
                }
            }

            $content = $this->container->get("translator")->trans(
                "Update Evaluates Setting %evaluate_info%",
                array('%evaluate_info%'=>implode(',', $logStr))
            );
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);

            return array('code'=>200, 'message'=>'ok');

        } catch (\Exception $e) {
            $this->dbal->rollBack();
            $this->logger->error($e->getMessage());

            return array('code'=>404, 'message'=>'数据保存失败');
        }
    }

    public function updateForOriginEvaluate(array $param = array())
    {
        $vccCode = empty($param['vccCode']) ? 0 : $param['vccCode'];
        $id = empty($param['id']) ? 0 : trim($param['id']);
        $name = empty($param['name']) ? 0 : trim($param['name']);
        $soundId = empty($param['sound']) ? 0 : trim($param['sound']);
        $playOrder = empty($param['play_order']) ? 0 : trim($param['play_order']);
        $retryTimes = empty($param['retry_times']) ? 0 : trim($param['retry_times']);
        $validKeys = empty($param['valid_keys']) ? '' : trim($param['valid_keys']);

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($id)) {
            return array('code'=>402, 'message'=>'ID不能为空');
        }

        if (empty($name)) {
            return array('code'=>402, 'message'=>'满意度名称为空');
        }

        if (empty($soundId)) {
            return array('code'=>404, 'message'=>'语音文件为空');
        }

        $this->dbal->beginTransaction();

        try {
            $data['vcc_id'] = $vid;
            $data['name'] = $name;
            $data['sound_id'] = $soundId;
            $data['play_order'] = $playOrder;
            $data['retry_times'] = $retryTimes;
            $data['valid_keys'] = $validKeys;
            $this->dbal->update('cc_evaluates', $data, array('id'=>$id));

            $this->dbal->commit();
            $logStr = array('id'=>$id);
            foreach ($data as $key => $v) {
                if ($key != 'vcc_id') {
                    $logStr[] = $key.'=>'.$v;
                }
            }

            $content = $this->container->get("translator")->trans(
                "Update Evaluates Setting %evaluate_info%",
                array('%evaluate_info%'=>implode(',', $logStr))
            );
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);

            return array('code'=>200, 'message'=>'ok');

        } catch (\Exception $e) {
            $this->dbal->rollBack();
            $this->logger->error($e->getMessage());

            return array('code'=>404, 'message'=>'数据保存失败');
        }
    }

    /**
     * get sound address by sound_id
     *
     * @param $soundId
     * @return array
     */
    public function getSoundAddress($soundId)
    {
        $res = $this->dbal->fetchAssoc('select address from win_sounds where id = :id',array('id' => $soundId));

        return $res['address'];
    }

    /**
     * 获取满意度配置的数据库ID
     *
     * @param $vccId
     * @return mixed
     */
    public function getEvaluateId($vccId)
    {
        $res = $this->dbal->fetchAssoc(
            "select id from cc_evaluates where vcc_id = :vcc_id",
            array('vcc_id' => $vccId)
        );
        $arr = array();
        $arr['id'] = $vccId;
        if (empty($res)) {
            $arr['action'] = 'insert';
        } else {
            $arr['action'] = 'update';
        }

        return $arr;
    }

    /**
     * @param string $vccCode
     * @param string $id
     * @return array|string
     */
    public function delete($vccCode, $id)
    {
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($id)) {
            return array('code'=>402, 'message'=>'参数id为空');
        }

        $this->dbal->beginTransaction();

        try {
            $idArr = explode(',', $id);
            foreach ($idArr as $v) {
                if (!is_numeric($v)) {
                    $errorMsg[] = array(sprintf("id [%s] 不是数字", $v));
                    break;
                }

                $this->dbal->delete("cc_evaluates", array('id' => $v, 'vcc_id'=>$vid));
            }

            if (!empty($errorMsg)) {
                $this->dbal->rollBack();

                return array('code'=>403, 'message'=>implode(',', $errorMsg));
            }

            $content = $this->container->get("translator")->trans(
                "Delete Evaluates Setting %evaluate_info%",
                array('%evaluate_info%'=>implode(',', $idArr))
            );
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_DELETE, $content);

            $this->dbal->commit();

            return array('code'=>200, 'message'=>"OK");
        } catch (\Exception $e) {
            $this->dbal->rollBack();
            $this->logger->error($e->getMessage());

            return array('code'=>404, 'message'=>'数据删除失败');
        }
    }

    /**
     * @param string  $vccCode
     * @param integer $id
     * @return array
     */
    public function getEvaluateInfo($vccCode, $id = 0)
    {
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($id)) {
            $data = $this->dbal->fetchAll(
                "SELECT id,name,sound_id,play_order,retry_times,valid_keys,evaluate_config FROM cc_evaluates WHERE vcc_id = :vcc_id ORDER BY play_order ASC",
                array('vcc_id'=>$vid)
            );
        } else {
            $data = $this->dbal->fetchAssoc(
                "SELECT id,name,sound_id,play_order,retry_times,valid_keys,evaluate_config FROM cc_evaluates WHERE vcc_id = :vcc_id AND id = :id",
                array('vcc_id'=>$vid, 'id'=>$id)
            );
        }

        return array('code'=>200, 'message'=>'ok', 'data'=>$data);
    }

    /**
     * @param array $param
     * @return array|string
     */
    public function evaluateDetailList(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $param['info'];

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (!empty($info)) {
            $info = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message'=>'info格式非json');
            }
        }

        $where = ' vcc_id = :vcc_id ';
        $condition['vcc_id'] = $vid;

        if (isset($info['filter'])) {
            /** 开始时间 */
            if (isset($info['filter']['start_time']) && !empty($info['filter']['start_time'])) {
                $startDate = $info['filter']['start_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始日期不正确', $startDate, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where.="AND call_time >= :start_date ";
                $condition['start_date'] = strtotime($startDate);
            }
            /** 结束时间 */
            if (isset($info['filter']['end_time']) && !empty($info['filter']['end_time'])) {
                $endDate = $info['filter']['end_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束日期不正确', $endDate, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where.="AND call_time <= :end_date ";
                $condition['end_date'] = strtotime($endDate);
            }

            if (isset($info['filter']['que_id']) && $info['filter']['que_id'] != '-1') {
                $where .= " AND que_id = :que_id ";
                $condition['que_id'] = $info['filter']['que_id'];
            }

            if (isset($info['filter']['agent_id']) && $info['filter']['agent_id'] != '-1') {
                $where .= " AND ag_id = :agent_id ";
                $condition['ag_id'] = $info['filter']['agent_id'];
            }

            if (isset($info['filter']['evaluate_result']) && $info['filter']['evaluate_result'] !== '') {
                $where .= " AND evaluate_result = :evaluate_result ";
                $condition['evaluate_result'] = $info['filter']['evaluate_result'];
            }

            if (isset($info['filter']['evaluate_id'])) {
                $where .= " AND evaluate_id = :evaluate_id ";
                $condition['evaluate_id'] = $info['filter']['evaluate_id'];
            }

            if (isset($info['filter']['call_id']) && !empty($info['filter']['call_id'])) {
                $where .= " AND call_id LIKE '%".$info['filter']['call_id']."%'";
            }
        }

        $count = $this->dbal->fetchColumn(
            'SELECT count(*) FROM win_agcdr_evaluate WHERE '.$where,
            $condition
        );

        /** @var  $queues (全部技能组数据) */
        $queues = $this->container->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vid, true, true);

        /** @var  $agents (全部坐席数据) */
        $agents = $this->container->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($vid, true);

        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_agcdr_evaluate', $info);

        $result = $this->dbal->fetchAll(
            'SELECT id,evaluate_id,call_id,ag_cdr_id,ag_id,que_id,evaluate_result,call_time,evaluate_time FROM win_agcdr_evaluate WHERE '.$where.'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $condition
        );

        $list = array();
        foreach ($result as $k => $v) {
            $list[$k] = $v;
            $list[$k]['que_name'] = isset($queues[$v['que_id']]) ? $queues[$v['que_id']] : '';
            $list[$k]['ag_num'] = isset($agents[$v['ag_id']]) ? $agents[$v['ag_id']] : '';
            $list[$k]['call_time'] = empty($v['call_time']) ? '' : date('Y-m-d H:i:s', $v['call_time']);
            $list[$k]['evaluate_time'] = empty($v['evaluate_time']) ? '' : date('Y-m-d H:i:s', $v['evaluate_time']);
            $list[$k]['evaluate_name'] = empty($v['evaluate_id']) ? '' : date('Y-m-d H:i:s', $v['evaluate_id']);
        }

        return array('code'=>200, 'message'=>'ok', 'total'=>$count, 'data'=>$list, 'totalPage'=>$page['totalPage']);
    }


    /**
     * 录音列表
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,// array 提供分页信息
     *                     )
     * @return array
     */
    public function recordList(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $endResult = $this->container->getParameter("end_type");
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        $evaluates = $this->container->getParameter('EVALUATES');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        /** @var array $addInfo 分页搜索相关信息 */
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where = isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND (ag_num LIKE '%".$addInfo['filter']['ag_num']."%' OR ag_name like '%".$addInfo['filter']['ag_num']."%') " : '';
            //呼叫类型
            if (isset($addInfo['filter']['call_type']) && !empty($addInfo['filter']['call_type'])) {
                $callType = (int) $addInfo['filter']['call_type'];
                if ($callType == 1) {
                    $where.= " AND (call_type = '1' OR call_type = '3' OR call_type = '5') ";
                } elseif ($callType == 2) {
                    $where.= " AND (call_type = '2' OR call_type = '4' OR call_type = '6') ";
                }
            }

            //坐席号码
            $where.= isset($addInfo['filter']['ag_phone']) && !empty($addInfo['filter']['ag_phone']) ?
                " AND ag_phone LIKE '%".$addInfo['filter']['ag_phone']."%' " : '';

            //客户号码
            $where.= isset($addInfo['filter']['cus_phone']) && !empty($addInfo['filter']['cus_phone']) ?
                " AND cus_phone LIKE '%".$addInfo['filter']['cus_phone']."%' " : '';

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $startTime = $addInfo['filter']['start_time'];
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where.="AND start_time >= UNIX_TIMESTAMP('$startTime')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $endTime = $addInfo['filter']['end_time'];
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where.="AND start_time <= UNIX_TIMESTAMP('$endTime')";
            }

            //时长大于
            if (isset($addInfo['filter']['ssecs']) && !empty($addInfo['filter']['ssecs'])) {
                $where.=" AND conn_secs >= :ssecs ";
                $params['ssecs'] =  $addInfo['filter']['ssecs'];
            }

            //时长小于
            if (isset($addInfo['filter']['esecs']) && !empty($addInfo['filter']['esecs'])) {
                $where.=" AND conn_secs <= :esecs ";
                $params['esecs'] =  $addInfo['filter']['esecs'];
            }

            //技能组id
            if (isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id'])) {
                $where.= " AND que_id = :que_id ";
                $params['que_id'] = $addInfo['filter']['que_id'];
            }
            //结束类型
            if (isset($addInfo['filter']['end_result']) && !empty($addInfo['filter']['end_result'])) {
                $where.= " AND endresult = :end_result ";
                $params['end_result'] = (int) $addInfo['filter']['end_result'];
            }
            //评价结果
            if (isset($addInfo['filter']['evaluates']) && !empty($addInfo['filter']['evaluates'])) {
                switch ($addInfo['filter']['evaluates']) {
                    /** 评价成功 */
                    case 1:
                        $where.= " AND evaluate >= :evaluate ";
                        $params['evaluate'] = (int) 0;
                        break;
                    /** 客户未评价 */
                    case 2:
                        $where.= " AND (evaluate = :evaluate OR evaluate = :evaluate1) ";
                        $params['evaluate'] = -2;
                        $params['evaluate1'] = -3;
                        break;
                    /** 客户挂机、坐席挂机 */
                    default:
                        $where.= " AND evaluate = :evaluate ";
                        $params['evaluate'] = (int) $addInfo['filter']['evaluates'];
                        break;
                }


            }
            if (isset($addInfo['filter']['id']) && $addInfo['filter']['id'] !== false) {
                $where.= " AND id IN (".$addInfo['filter']['id'].")";
            }

            if (isset($addInfo['filter']['group_id']) && $addInfo['filter']['group_id'] != '-1') {
                $where .= " AND group_id = {$addInfo['filter']['group_id']} ";
            }
            //中继号码
            if (isset($addInfo['filter']['serv_num']) && !empty($addInfo['filter']['serv_num'])) {
                $where .= " AND serv_num=".$addInfo['filter']['serv_num'];
            }
        }

        /** @var  $authority (获取数据权限)*/
        $authority = $this->container->get("icsoc_core.common.class")->getAuthorityCondition('ag_id', 'que_id', 1);
        if ($authority === false) {
            return array(
                'code' => 404,
                'message' => '权限内无任何数据',
            );
        } else {
            $where .= $authority.' ';
        }

        $params['vcc_id'] = $vccId;
        $params['record_mark'] = 1;

        $adsDbal = $this->container->get('doctrine.dbal.ads_connection');
        $count = $adsDbal->fetchColumn(
            'SELECT count(*) FROM win_agcdr WHERE vcc_id = :vcc_id AND record_mark = :record_mark '.$where,
            $params
        );
        $forPageParam = $this->container->get('icsoc_data.model.report')->pageForAdsSearch($param['forPageParam'], $addInfo['pagination']['rows'], $count);
        $where .= $forPageParam['where'];
        $orderBy = $forPageParam['orderBy'];
        $sqlLimit = $forPageParam['sqlLimit'];
        $isReversed = $forPageParam['isReversed'];
        $isChangeRowlist = $forPageParam['isChangeRowlist'];
        $totalPage = $forPageParam['totalPage'];

        if (empty($addInfo['export'])) {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,serv_num,ag_phone,cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate,evaluate_obj ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.$orderBy.$sqlLimit,
                $params
            );
        } else {
            $rows = $adsDbal->fetchAll(
                "SELECT id,ag_id,group_id,ag_name,ag_num,que_name,call_type,call_id,serv_num,ag_phone,cus_phone,start_time,end_time,conn_secs,record_file,endresult,evaluate,evaluate_obj ".
                "FROM win_agcdr ".
                "WHERE vcc_id = :vcc_id AND record_mark = :record_mark ".$where.
                $orderBy,
                $params
            );
        }

        /** @var array $evaluates 满意度信息 */
        $evaluatesArr = $this->container->get('icsoc_data.model.evaluate')->getEvaluateInfo($vccCode);
        $evaluatesArr = isset($evaluatesArr['data']) ? $evaluatesArr['data'] : array();

        if ($isReversed == true) {
            $rows = array_reverse($rows);
        }
        $result = array();
        foreach ($rows as $k => $v) {
            $result[$k]['server_num'] = $v['serv_num'];
            $result[$k]['ag_id'] = $v['ag_id'];
            $result[$k]['id'] = $v['id'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $v['cus_phone'];
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['record_file'] = $v['record_file'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            //$result[$k]['ag_num'] = $v['ag_name']." ".$v['ag_num'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['call_id'] = $v['call_id'];
            $result[$k]['group_id'] = $v['group_id'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->RCALLTYPE[1];
            } else {
                $result[$k]['call_type'] = $this->RCALLTYPE[2];
            }
            $result[$k]['evaluate'] = isset($evaluates[$v['evaluate']]) ?  $evaluates[$v['evaluate']] : '';
            switch ($v['evaluate']) {
                case -4:
                case -1:
                    $result[$k]['evaluate'] = isset($evaluates[$v['evaluate']]) ?  $evaluates[$v['evaluate']] : '';
                    break;
                case -2:
                case -3:
                    $result[$k]['evaluate'] = '客户未评价';
                    break;
                default:
                    $result[$k]['evaluate'] = '评价成功';
                    break;
            }

            $evaluateObj = json_decode($v['evaluate_obj'], true);
            if (json_last_error() != JSON_ERROR_NONE) {
                $this->logger->error(
                    sprintf(
                        'agcdr id is [%s] Json decode the response [%s] fails, error [%]',
                        $v['id'],
                        $v['evaluate_obj'],
                        json_last_error()
                    )
                );
            }

            foreach ($evaluatesArr as $evaluate) {
                $result[$k]['evaluate_'.$evaluate['id']] = isset($evaluateObj[$evaluate['id']]) ?
                    $evaluateObj[$evaluate['id']] : '未评价';
            }
        }

        return array(
            'code'=>200,
            'message'=>'ok',
            'total' => $count,
            'data'=>$result,
            'totalPage' => $totalPage,
            'isChangeRowlist' => $isChangeRowlist
        );
    }

    /**
     * 从elasticsearch+mongodb中获取满意度评价数据
     *
     * @param array $param
     * @return array
     */
    public function recordListFromElasticsearch(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        //$evaluates = $this->container->getParameter('EVALUATES');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        /** @var array $info 分页搜索相关信息 */
        if (!empty($info)) {
            $info = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $rows = empty($info['pagination']['rows']) ? 10 : $info['pagination']['rows'];
        $page = empty($info['pagination']['page']) ? 1 : $info['pagination']['page'];
        $order = empty($info['sort']['order']) ? 'desc' : $info['sort']['order'];
        $field = empty($info['sort']['field']) ? 'start_time' : $info['sort']['field'];

        $type = "win_agcdr";
        $condition = array(
            'fixup' => array(
                'index' => 'agcdr',
                'type' => $type,
                'rows' => $rows == -1 ? 1000 : $rows,
                'page' => $page,
                'order' => $order,
                'field' => $field,
            ),
            'term' => array('vcc_id' => array('type' => 'match', 'value' => (int) $vccId)),
        );
        $time = $this->container->get("icsoc_core.common.class")->rolesCanSearchAllReportDatas($info['filter']['start_time'], $info['filter']['end_time'], 'date');
        if ($time == 'no') {
            $condition['term']['vcc_id'] = array('type' => 'match', 'value' => 0);
        }

        if (isset($info['filter'])) {
            //坐席工号
            if (isset($info['filter']['ag_num']) && $info['filter']['ag_num'] != '-1') {
                $agId = (int) $info['filter']['ag_num'];
                $condition['term']['ag_id'] = array('type' => 'match', 'value' => $agId);
            }

            //呼叫类型
            if (isset($info['filter']['call_type']) && !empty($info['filter']['call_type'])) {
                $callType = (int) $info['filter']['call_type'];
                if ($callType == 1) {
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '1,3,5');
                } elseif ($callType == 2) {
                    //11转内线 12转电话
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '2,4,6,11,12');
                }
            }

            //满意度评价结果
            if (isset($info['filter']['evaluates']) && is_array($info['filter']['evaluates'])) {
                foreach ($info['filter']['evaluates'] as $evaluate) {
                    if ($evaluate == '-3' || $evaluate == '-1' || $evaluate == '-2' || $evaluate == '-4') {
                        $condition['term']['evaluate'] = array('type' => 'match', 'value' => (int) $evaluate);
                    } else {
                        $condition['term'][$evaluate] = array('type' => 'match', 'value' => 1);
                        $condition['term']['evaluate'] = array('type' => 'range', 'value' => 1, 'field' => 'evaluate', 'operation' => 'gte');
                    }
                }
            }

            //坐席号码
            if (isset($info['filter']['ag_phone']) && !empty($info['filter']['ag_phone'])) {
                $condition['term']['ag_phone'] = array('type' => 'wildcard', 'value' => $info['filter']['ag_phone']);
            }

            //客户号码
            if (isset($info['filter']['cus_phone']) && !empty($info['filter']['cus_phone'])) {
                $condition['term']['cus_phone'] = array('type' => 'wildcard', 'value' => $info['filter']['cus_phone']);
            }

            //开始时间
            if (isset($info['filter']['start_time']) && !empty($info['filter']['start_time'])) {
                $startTime = $info['filter']['start_time'];
                if (isset($time['startTime'])) {
                    $startTime = $time['startTime'];
                }
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $condition['term']['start_time'] = array('type' => 'range', 'value' => strtotime($startTime), 'field' => 'start_time', 'operation' => 'gte');
            }

            //结束时间
            if (isset($info['filter']['end_time']) && !empty($info['filter']['end_time'])) {
                $endTime = $info['filter']['end_time'];
                if (isset($time['endTime'])) {
                    $endTime = $time['endTime'];
                }
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $condition['term']['end_time'] = array('type' => 'range', 'value' => strtotime($endTime), 'field' => 'start_time', 'operation' => 'lte');
            }

            //时长大于
            if (isset($info['filter']['ssecs']) && !empty($info['filter']['ssecs'])) {
                $ssecs = (int) $info['filter']['ssecs'];
                $condition['term']['ssecs'] = array('type' => 'range', 'value' => $ssecs, 'field' => 'conn_secs', 'operation' => 'gte');
            }

            //时长小于
            if (isset($info['filter']['esecs']) && !empty($info['filter']['esecs'])) {
                $esecs = (int) $info['filter']['esecs'];
                $condition['term']['esecs'] = array('type' => 'range', 'value' => $esecs, 'field' => 'conn_secs', 'operation' => 'lte');
            }

            //技能组id
            if (isset($info['filter']['que_id']) && $info['filter']['que_id'] != '-1') {
                $queId = (int) $info['filter']['que_id'];
                $condition['term']['que_id'] = array('type' => 'match', 'value' => $queId);
            }
            //结束类型
            if (isset($info['filter']['end_result']) && !empty($info['filter']['end_result'])) {
                $condition['term']['endresult'] = array('type' => 'match', 'value' => $info['filter']['end_result']);
            }
            //评价结果
            /*if (isset($info['filter']['evaluates']) && !empty($info['filter']['evaluates'] && is_string($info['filter']['evaluates']))) {
                $evaluate = (int) $info['filter']['evaluates'];
                if ($evaluate == -3 || $evaluate == -1 || $evaluate == -2 || $evaluate == -4) {
                    $condition['term']['evaluate'] = array('type' => 'match', 'value' => $evaluate);
                } else {
                    $condition['term']['evaluate'] = array(
                        'type' => 'multiNomatch',
                        'multi' => 'multi' ,
                        'value' => array(-1,-2,-3,-4),
                    );
                }
            }*/
            if (isset($info['filter']['id']) && $info['filter']['id'] !== false) {
                $condition['term']['id'] = array('type' => 'should', 'value' => $info['filter']['id']);
            }

            if (isset($info['filter']['group_id']) && $info['filter']['group_id'] != '-1') {
                $condition['term']['group_id'] = array('type' => 'should', 'value' => $info['filter']['group_id']);
            }
            //中继号码
            if (isset($info['filter']['serv_num']) && !empty($info['filter']['serv_num'])) {
                $condition['term']['serv_num'] = array('type' => 'match', 'value' => $info['filter']['serv_num']);
            }
        }

        $condition['term']['record_mark'] = array('type' => 'match', 'value' => 1);
        /** @var  $authority (获取数据权限) */
        $authority = $this->container->get("icsoc_core.common.class")->getAuthorityConditionForElasearch('ag_id', 'que_id', 1);
        if ($authority === false) {
            return array(
                'code' => 404,
                'message' => '权限内无任何数据',
            );
        } else {
            if (!empty($authority['ag_id']) && $info['filter']['ag_num'] == '-1') {
                $condition['term']['ag_id'] = array('type' => 'terms', 'value' => $authority['ag_id']);
            }
            if (!empty($authority['que_id']) && $info['filter']['que_id'] == '-1') {
                $condition['term']['que_id'] = array('type' => 'terms', 'value' => $authority['que_id']);
            }
            if (!empty($authority['group_id']) && $info['filter']['group_id'] == '-1') {
                $condition['term']['group_id'] = array('type' => 'terms', 'value' => $authority['group_id']);
            }
        }
        //查看是否拥有查看用户号码的权限
        $cusPhoneAuthority = $this->container->get("icsoc_core.common.class")->getWhetherHaveAuthority('icsoc_show_cus_phone');
        $condition['export'] = empty($info['export']) ? 0 : 1;
        $rows = $this->container->get('icsoc_data.model.report')->getDataFromESAndMongo($condition, 'win_agcdr');
        $resultData = $rows['data'];
        $count = $rows['count'];
        $totalPages = $rows['totalPages'];
        $evaluatesConfig = $this->container->get('icsoc_data.model.evaluate')
            ->getEvaluateConfig(
                array(
                    'vccId'=> $vccId
                )
            );
        $evaluatesConfig = json_decode($evaluatesConfig, true);
        $result = array();

        foreach ($resultData as $k => $v) {
            $result[$k]['server_num'] = $v['serv_num'];
            $result[$k]['vcc_id'] = (string) $v['vcc_id'];
            $result[$k]['ag_id'] = $v['ag_id'];
            $result[$k]['agcdr_id'] = isset($v['agcdr_id']) ? (string) $v['agcdr_id'] : '';
            $result[$k]['id'] = (string) $v['_id'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $this->container->get("icsoc_core.common.class")->concealCusPhone($v['cus_phone'], $cusPhoneAuthority);
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['record_file'] = $v['record_file'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['call_id'] = (string) $v['call_id'];//mongo中callID是bigInt型，需要将整型转换成字符串，避免js出错
            $result[$k]['group_id'] = $v['group_id'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            if (!empty($evaluatesConfig) && isset($evaluatesConfig)) {
                foreach ($evaluatesConfig as $key => $evaluateConfig) {
                    if ($v['evaluate'] < 0) {
                        $result[$k][$evaluateConfig['id']] = $v['evaluate'];
                        switch ($v['evaluate']) {
                            case -1:
                                $result[$k][$evaluateConfig['id']] = '客户挂机';
                                break;
                            case -2:
                                $result[$k][$evaluateConfig['id']] = '未评价挂机';
                                break;
                            case -3:
                                $result[$k][$evaluateConfig['id']] = '未评价挂机';
                                break;
                            case -4:
                                $result[$k][$evaluateConfig['id']] = '坐席挂机';
                                break;
                        }
                    } else {
                        if (isset($v[$evaluateConfig['id']])) {
                            $result[$k][$evaluateConfig['id']] = $v[$evaluateConfig['id']];
                            if ($v[$evaluateConfig['id']] == null) {
                                $result[$k][$evaluateConfig['id']] = '未评价';
                            }
                        } else {
                            $result[$k][$evaluateConfig['id']] = '未评价';
                        }
                    }
                }
            }

            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->RCALLTYPE[1];
            } else {
                $result[$k]['call_type'] = $this->RCALLTYPE[2];
            }
            unset($resultData[$k]);
        }
        unset($resultData);

        return array(
            'code'=>200,
            'message'=>'ok',
            'total' => $count,
            'data'=>$result,
            'totalPage' => $totalPages,
            'page' => $page
        );
    }


    /**
     * 当满意度配置为原来的老格式是，从elasticsearch+mongodb中获取满意度评价数据
     *
     * @param array $param
     * @return array
     */
    public function recordListFromElasticsearchForOldEvaluateConfig(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        /** @var array $info 分页搜索相关信息 */
        if (!empty($info)) {
            $info = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $rows = empty($info['pagination']['rows']) ? 10 : $info['pagination']['rows'];
        $page = empty($info['pagination']['page']) ? 1 : $info['pagination']['page'];
        $order = empty($info['sort']['order']) ? 'desc' : $info['sort']['order'];
        $field = empty($info['sort']['field']) ? 'start_time' : $info['sort']['field'];

        $type = "win_agcdr";
        $condition = array(
            'fixup' => array(
                'index' => 'agcdr',
                'type' => $type,
                'rows' => $rows == -1 ? 1000 : $rows,
                'page' => $page,
                'order' => $order,
                'field' => $field,
            ),
            'term' => array('vcc_id' => array('type' => 'match', 'value' => (int) $vccId)),
        );
        $time = $this->container->get("icsoc_core.common.class")->rolesCanSearchAllReportDatas($info['filter']['start_time'], $info['filter']['end_time'], 'date');
        if ($time == 'no') {
            $condition['term']['vcc_id'] = array('type' => 'match', 'value' => 0);
        }

        if (isset($info['filter'])) {
            //坐席工号；
            if (isset($info['filter']['ag_num']) && $info['filter']['ag_num'] != '-1') {
                $agId = (int) $info['filter']['ag_num'];
                $condition['term']['ag_id'] = array('type' => 'match', 'value' => $agId);
            }

            //呼叫类型
            if (isset($info['filter']['call_type']) && !empty($info['filter']['call_type'])) {
                $callType = (int) $info['filter']['call_type'];
                if ($callType == 1) {
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '1,3,5');
                } elseif ($callType == 2) {
                    //11转内线 12 转电话
                    $condition['term']['call_type'] = array('type' => 'should', 'value' => '2,4,6,11,12');
                }
            }

            //坐席号码
            if (isset($info['filter']['ag_phone']) && !empty($info['filter']['ag_phone'])) {
                $condition['term']['ag_phone'] = array('type' => 'wildcard', 'value' => $info['filter']['ag_phone']);
            }

            //客户号码
            if (isset($info['filter']['cus_phone']) && !empty($info['filter']['cus_phone'])) {
                $condition['term']['cus_phone'] = array('type' => 'wildcard', 'value' => $info['filter']['cus_phone']);
            }

            //开始时间
            if (isset($info['filter']['start_time']) && !empty($info['filter']['start_time'])) {
                $startTime = $info['filter']['start_time'];
                if (isset($time['startTime'])) {
                    $startTime = $time['startTime'];
                }
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $startTime, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $condition['term']['start_time'] = array('type' => 'range', 'value' => strtotime($startTime), 'field' => 'start_time', 'operation' => 'gte');
            }

            //结束时间
            if (isset($info['filter']['end_time']) && !empty($info['filter']['end_time'])) {
                $endTime = $info['filter']['end_time'];
                if (isset($time['endTime'])) {
                    $endTime = $time['endTime'];
                }
                $msg =  $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $endTime, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $condition['term']['end_time'] = array('type' => 'range', 'value' => strtotime($endTime), 'field' => 'start_time', 'operation' => 'lte');
            }

            //时长大于
            if (isset($info['filter']['ssecs']) && !empty($info['filter']['ssecs'])) {
                $ssecs = (int) $info['filter']['ssecs'];
                $condition['term']['ssecs'] = array('type' => 'range', 'value' => $ssecs, 'field' => 'conn_secs', 'operation' => 'gte');
            }

            //时长小于
            if (isset($info['filter']['esecs']) && !empty($info['filter']['esecs'])) {
                $esecs = (int) $info['filter']['esecs'];
                $condition['term']['esecs'] = array('type' => 'range', 'value' => $esecs, 'field' => 'conn_secs', 'operation' => 'lte');
            }

            //技能组id
            if (isset($info['filter']['que_id']) && $info['filter']['que_id'] != '-1') {
                $queId = (int) $info['filter']['que_id'];
                $condition['term']['que_id'] = array('type' => 'match', 'value' => $queId);
            }
            //结束类型
            if (isset($info['filter']['end_result']) && !empty($info['filter']['end_result'])) {
                $condition['term']['endresult'] = array('type' => 'match', 'value' => $info['filter']['end_result']);
            }
            //评价结果
            if (isset($info['filter']['evaluates']) && !empty($info['filter']['evaluates'])) {
                $evaluate = (int) $info['filter']['evaluates'];
                if ($evaluate == -3 || $evaluate == -1 || $evaluate == -2 || $evaluate == -4) {
                    $condition['term']['evaluate'] = array('type' => 'match', 'value' => $evaluate);
                } else {
                    $condition['term']['evaluate'] = array(
                        'type' => 'multiNomatch',
                        'multi' => 'multi' ,
                        'value' => array(-1,-2,-3,-4),
                    );
                }
            }
            if (isset($info['filter']['id']) && $info['filter']['id'] !== false) {
                $condition['term']['id'] = array('type' => 'should', 'value' => $info['filter']['id']);
            }

            if (isset($info['filter']['group_id']) && $info['filter']['group_id'] != '-1') {
                $condition['term']['group_id'] = array('type' => 'should', 'value' => $info['filter']['group_id']);
            }
            //中继号码
            if (isset($info['filter']['serv_num']) && !empty($info['filter']['serv_num'])) {
                $condition['term']['serv_num'] = array('type' => 'match', 'value' => $info['filter']['serv_num']);
            }
        }

        $condition['term']['record_mark'] = array('type' => 'match', 'value' => 1);
        /** @var  $authority (获取数据权限) */
        $authority = $this->container->get("icsoc_core.common.class")->getAuthorityConditionForElasearch('ag_id', 'que_id', 1);
        if ($authority === false) {
            return array(
                'code' => 404,
                'message' => '权限内无任何数据',
            );
        } else {
            if (!empty($authority['ag_id']) && $info['filter']['ag_num'] == '-1') {
                $condition['term']['ag_id'] = array('type' => 'terms', 'value' => $authority['ag_id']);
            }
            if (!empty($authority['que_id']) && $info['filter']['que_id'] == '-1') {
                $condition['term']['que_id'] = array('type' => 'terms', 'value' => $authority['que_id']);
            }
            if (!empty($authority['group_id']) && $info['filter']['group_id'] == '-1') {
                $condition['term']['group_id'] = array('type' => 'terms', 'value' => $authority['group_id']);
            }
        }
        //查看是否拥有查看用户号码的权限
        $cusPhoneAuthority = $this->container->get("icsoc_core.common.class")->getWhetherHaveAuthority('icsoc_show_cus_phone');
        $condition['export'] = empty($info['export']) ? 0 : 1;
        $rows = $this->container->get('icsoc_data.model.report')->getDataFromESAndMongo($condition, 'win_agcdr', array('field' => $field, 'order' => $order));
        $resultData = $rows['data'];
        $count = $rows['count'];
        $totalPages = $rows['totalPages'];

        /** @var array $evaluates 满意度信息 */
        $evaluatesArr = $this->container->get('icsoc_data.model.evaluate')->getEvaluateInfo($vccCode);
        $evaluatesArr = isset($evaluatesArr['data']) ? $evaluatesArr['data'] : array();

        $result = array();
        foreach ($resultData as $k => $v) {
            $result[$k]['server_num'] = $v['serv_num'];
            $result[$k]['vcc_id'] = (string) $v['vcc_id'];
            $result[$k]['ag_id'] = $v['ag_id'];
            $result[$k]['agcdr_id'] = isset($v['agcdr_id']) ? (string) $v['agcdr_id'] : '';
            $result[$k]['id'] = (string) $v['_id'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['cus_phone'] = $this->container->get("icsoc_core.common.class")->concealCusPhone($v['cus_phone'], $cusPhoneAuthority);
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['record_file'] = $v['record_file'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['call_id'] = (string) $v['call_id'];//mongo中callID是bigInt型，需要将整型转换成字符串，避免js出错
            $result[$k]['group_id'] = $v['group_id'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            $result[$k]['evaluate'] = $v['evaluate'];
            switch ($v['evaluate']) {
                case 1:
                    $result[$k]['evaluate'] = '评价成功';
                    break;
                case -1:
                    $result[$k]['evaluate'] = '客户挂机';
                    break;
                case -2:
                    $result[$k]['evaluate'] = '未评价挂机';
                    break;
                case -3:
                    $result[$k]['evaluate'] = '未评价挂机';
                    break;
                case -4:
                    $result[$k]['evaluate'] = '坐席挂机';
                    break;
                default:
                    $result[$k]['evaluate'] = '评价成功';
                    break;
            }
            if ($v['call_type'] == 1 || $v['call_type'] == 3 || $v['call_type'] == 5) {
                $result[$k]['call_type'] = $this->RCALLTYPE[1];
            } else {
                $result[$k]['call_type'] = $this->RCALLTYPE[2];
            }
            if (!empty($evaluatesArr)) {
                foreach ($evaluatesArr as  $evaluate) {
                    if (isset($v['evaluate_'.$evaluate['id']])) {
                        $result[$k]['evaluate_'.$evaluate['id']] = $v['evaluate_'.$evaluate['id']];
                    }
                }
            }
            unset($resultData[$k]);
        }
        unset($resultData);

        return array(
            'code'=>200,
            'message'=>'ok',
            'total' => $count,
            'data'=>$result,
            'totalPage' => $totalPages,
            'page' => $page
        );
    }

    /**
     * 获取满意度配置信息
     * @param array $param
     * @return mixed
     */
    public function getEvaluateConfig($param = array())
    {
        $vccId = $param['vccId'];
        $evaluate = $this->dbal->fetchAssoc(
            'select evaluate_config from cc_evaluates_config where vcc_id = :vcc_id',
            array('vcc_id' => $vccId)
        );

        return $evaluate['evaluate_config'];
    }

    /**
     * 通过vccId获取该企业的满意度配置是不是新的满意度
     *
     * @param $vccId
     * @return int
     */
    public function getEvaluateVerByVccId($vccId = '')
    {
        $evaluateVer = $this->dbal->fetchColumn(
            'select evaluate_ver from cc_ccods where vcc_id = :vcc_id',
            array('vcc_id' => $vccId)
        );

        return (int) $evaluateVer;
    }
}
